package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * JVM级别锁：synchronized
 * <p>
 * 分布式环境不适用
 * <p>
 * 模拟场景：
 * Pod1: 8080   url :  http://localhost:8080/stock/sync
 * <p>
 * Pod2: 8081   url :  http://localhost:8081/stock/sync
 * IDEA  配置：  VM-Option: -Dserver.port=8081
 */
@RestController
public class IndexController_JVM {

    @Autowired
    private StringRedisTemplate redisTemplate;

    int i = 1;

    @RequestMapping("/jvmLock/reduceStock")
    public String reduceStock() {
        String msg = "";

        //JVM锁，this指当前线程操作对象
        synchronized (this) {
            int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("stock", realStock + "");
                msg = "当前客户:" + (i++) + " 购买成功，剩余:" + realStock;
                System.out.println(msg);
            } else {
                msg = "购买失败，库存不足";
                System.out.println(msg);
            }
            return msg;
        }

    }

}
